package cn.javabb.project.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.javabb.common.exception.GenException;
import cn.javabb.common.model.domain.AjaxResult;
import cn.javabb.framework.model.GenConfig;
import cn.javabb.framework.model.GenModel;
import cn.javabb.framework.util.DBUtil;
import cn.javabb.framework.web.controller.BaseController;
import cn.javabb.project.entity.GenTable;
import cn.javabb.project.entity.SysDataSource;
import cn.javabb.project.service.GenService;
import cn.javabb.project.service.GenTableService;
import cn.javabb.project.service.SysDataSourceService;
import cn.javabb.project.util.GenUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc:
 * @author: javabb (javabob(a)163.com)
 * @create: 2021/04/28 11:28
 */
@Slf4j
@Api(tags = "代码生成管理")
@RequestMapping("/gen")
@RestController
public class GenController extends BaseController {
    @Value("${gen.rootPath}")
    private String rootPath;
    @Autowired
    private GenService genService;
    @Autowired
    private SysDataSourceService sysDataSourceService;
    @Autowired
    private GenTableService genTableService;

    /**
     * 分页查询table
     *
     * @param table
     * @return
     */
    @ApiOperation("分页查询生成表")
    @GetMapping("/tables")
    public Object tableList(GenTable table) {
        startPage();
        List<GenTable> list = genTableService.list(table);
        return getDataTable(list);
    }

    /**
     * 查询数据库table
     *
     * @return
     */
    @ApiOperation("查询所有表")
    @GetMapping("/db/tables")
    public Object dbTables(Long dscId) {
        try {
            List<GenTable> tableList = genService.listDbTableByDsId(dscId);
            return AjaxResult.success(tableList);
        } catch (SQLException e) {
            log.error("获取数据库表异常", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询数据库列表
     *
     * @return
     */
    @ApiOperation("查询所有数据源")
    @GetMapping("/db/list")
    public Object dbList() {

        List<SysDataSource> list = sysDataSourceService.list();
        return list;
    }

    /**
     * 导入表结构
     *
     * @return
     */
    @ApiOperation("根据数据源导入生成表")
    @PostMapping("/importTables")
    public Object importTables(@RequestBody GenConfig config) {
        try {
            String projectId = genService.getGenTables(config);
            return AjaxResult.success("生成成功", projectId);
        } catch (Exception e) {
            log.error("导入异常,e={}", e.getMessage());
            return AjaxResult.error("导入异常" + e.getMessage());
        }
    }

    @ApiOperation("生成代码")
    @PostMapping("/gen")
    public Object toGen(@RequestBody GenConfig config) {
        if (config == null || StrUtil.isBlank(config.getProjectId())) {
            throw new GenException("ProjectId不能为空");
        }
        try {
            genService.genCode(config);
            String outPath = config.getProjectId() + "/" + config.getProjectName() + ".zip";
            // 打包
            ZipUtil.zip(genService.getProjectDir() + config.getProjectId(),
                    genService.getDownloadDir() + outPath);

            return AjaxResult.success("", outPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("生成代码异常");
        }

    }

    /**
     * 打开生成代码的本地目录.本地调试用
     *
     * @param projectId
     */
    @ApiOperation("打开目录,本地调试用")
    @GetMapping("/open")
    public void toGen(String projectId) {
        if (StrUtil.isBlank(projectId)) {
            throw new GenException("ProjectId不能为空");
        }
        String projectPath = rootPath + projectId;
        GenUtil.open(projectPath);
    }


    @ApiOperation("下载代码")
    @GetMapping("/download")
    public void toDownload(String file, HttpServletResponse response) {
        if (StrUtil.isBlank(file)) {
            throw new GenException("参数错误");
        }
        File outFile = new File(genService.getDownloadDir() + file);
        if (!outFile.exists()) return;
        // 设置下载文件header
        response.setContentType("application/force-download");
        String fileName = outFile.getName();
        try {
            fileName = URLEncoder.encode(fileName, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        // 输出文件流
        OutputStream os = null;
        BufferedInputStream is = null;
        try {
            os = response.getOutputStream();
            is = new BufferedInputStream(new FileInputStream(outFile));
            byte[] bytes = new byte[1024 * 256];
            int len;
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
